/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function (l1, l2) {
  let arr1 = [], arr2 = [],arr3 = [],carry = 0, res = new ListNode();
  while (l1) {
    arr1.push(l1.val)
  }
  while (l2) {
    arr2.push(l2.val)
  }

  while (arr1 || arr2 || carry) {
    let a = arr1 ? arr1.pop() : 0, b = arr2 ? arr2.pop() : 0
    arr3.push((a + b + carry) % 10)
    carry = Math.floor((a + b+carry) / 10)

  }

  for (let i = arr3.length - 1; i >= 0; i--) {
    res.val = new ListNode(arr3[i])
    res = res.next
  }

  return res
};